<?php
/**
 * Geocontexter
 * @link http://code.google.com/p/geocontexter/
 * @package Geocontexter
 */

/**
 * Admin index controller
 *
 *
 * @package Geocontexter
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @author Armand Turpel <geocontexter@gmail.com>
 * @version $Rev$ / $LastChangedDate$ / $LastChangedBy$
 */

namespace Gospecies\Controller;

use Zend\View\Model\JsonModel;
use Gospecies\Controller\AbstractIdentityJsonController;


class JsonRecordAddController extends AbstractIdentityJsonController
{

    public function indexAction()
    {
        // check permission if id_group is at least "contributor".
        // users of those groups can only add records
        //
        if (isset($this->get_identity()->id_group)) {
            if (((int)$this->get_identity()->id_status != 200) || ((int)$this->get_identity()->id_group >= 400)) {
                return new JsonModel(array('error' => 'permission denied'));
            }
        } else {
            return new JsonModel(array('error' => 'permission denied'));
        }

        $images = $this->request->getPost()->images;

        $media_folder = '';

        if (isset($images) && (count($images) > 0)) {
          $media_folder = md5(time() . var_export($this->request->getPost(),true));
        }

        $id_attribute_group = $this->request->getPost()->id_attribute_group;
        $error = array();

        $params = array('id_item'            => $this->request->getPost()->id_item,
                        'id_owner'           => $this->get_identity()->id_user,
                        'id_modifier'        => $this->get_identity()->id_user,
                        'id_project'         => $this->request->getPost()->id_project,
                        'id_attribute_group' => $id_attribute_group,
                        'id_status'          => 1000,
                        'date_record_start'  => $this->request->getPost()->date_record_start,
                        'date_record_end'    => $this->request->getPost()->date_record_end,
                        'timezone'           => 'Europe/Berlin',
                        'media_folder_hash'  => $media_folder
                       );

        if ($params['id_item'] === null) {
            $error[] = 'id_item isnt defined';
        }

        if ($params['date_record_start'] === null) {
            $error[] = 'date_record_start isnt defined';
        }

        if ($params['date_record_end'] === null) {
            $error[] = 'date_record_end isnt defined';
        }

        $geometry = $this->request->getPost()->geom;

        if (false !== strstr($geometry, ',')) {
            $_geom = explode(',', $geometry);
        } elseif (false !== strstr($geometry, ' ')) {
            $_geom = explode(' ', $geometry);
        } else {
            $error[] = 'Latitude/Longitude isnt separated by space or comma.';
        }

        if (!isset($_geom[0]) || !isset($_geom[1])) {
            $error[] = 'Geographic reference is wrong';
        } else {
            $params['geom_point'] = $this->build_geometry(trim($_geom[0]), trim($_geom[1]));
        }

        $attributes = $this->request->getPost()->attributes;

        if (is_array($attributes) && (count($attributes) > 0 )) {

            $AttributeHstoreEncode = $this->CoreModel('AttributeHstoreEncode2');

            $_attributes = array();

            foreach ($attributes as $attr) {
              if (is_array($attr) && isset($attr['name']) && isset($attr['value'])) {
                $_attributes[$attr['name']] = $attr['value'];
              }
            }

            $serialized_attributes     = $AttributeHstoreEncode->encode( $id_attribute_group, $_attributes, '$$' );

            $params['attribute_value'] = $serialized_attributes['hstore'];
        }

            if (count($error) > 0) {
                return new JsonModel(array('error' => $error));
            }

            $RecordAdd = $this->CoreModel('RecordAdd');

            try {

                $id_record  = $RecordAdd->run( $params );

          if (!empty($media_folder)) {

              $tmp_image_path = $this->sessionOffsetGet('tmp_image_path');

              $RecordImageAdd    = $this->CoreModel('RecordImageAdd');


              mkdir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder);
              mkdir(GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder . '/image');

              $tmp_folder = GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path;


              $x = 0;

              foreach ($images['i_name'] as $img) {

                $info = getimagesize ( $tmp_folder . '/' . $img );

                $params = array('id_record'   => $id_record,
                                'title'       => $images['i_title'][$x],
                                'description' => $images['i_description'][$x],
                                'media'       => array('file_name'   => $img,
                                                       'file_mime'   => $info['mime'],
                                                       'file_width'  => $info[0],
                                                       'file_height' => $info[1],
                                                       'file_size'   => filesize($tmp_folder . '/' . $img))
                                );

                $RecordImageAdd->run($params);

                $x++;
              }

              $RecordImageUpload = $this->CoreModel('RecordImageUpload');

              $params  = array('image_folder_path'        => GEOCONTEXTER_ROOT . '/public/data/gc_record/' . $id_record . '_' . $media_folder . '/image',
                               'source_image_folder_path' => GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path,
                               'delete_source'            => true
                      );

              $result  = $RecordImageUpload->run( $params );

          }
            return new JsonModel(array('result' => array('id_record' => $id_record)));

        } catch (\Exception $e) {

            $this->default_error = "Error\n File: " . __file__ . "\nLine: " . __line__ . "\nError: " . $e->__toString();

            return new JsonModel(array('error' => $this->default_error));

        }
    }
    private function build_geometry($latitude, $longitude)
    {
        return "ST_GeometryFromText('POINT({$longitude} {$latitude})',4326)";
    }

    public function imageAddAction()
    {
        require(GEOCONTEXTER_ROOT . '/public/library/jQuery-File-Upload/GospeciesUploadHandler.php');

        if (true === $this->sessionOffsetExists('tmp_image_path')) {

          $tmp_image_path = $this->sessionOffsetGet('tmp_image_path');

        } else {

          $tmp_image_path = md5(time() . rand());
          mkdir(GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path);
          $this->sessionOffsetSet('tmp_image_path', $tmp_image_path);

        }

        $options = array('upload_dir'        => GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path . '/',
                         'upload_url'        => $this->getBaseUrl().'/data/tmpuploads/' . $tmp_image_path . '/',
                         'image_folder_name' => $tmp_image_path);

        $upload_handler = new \UploadHandler($options);
        exit;
    }

    public function imageRemoveAction()
    {
      $tmp_image_path = $this->sessionOffsetGet('tmp_image_path');

      $image_name = preg_replace("/(\.\.)|(\/)|(\\\)/","",$this->request->getPost()->image);

      unlink(GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path . '/' . $image_name);
      unlink(GEOCONTEXTER_ROOT . '/public/data/tmpuploads/' . $tmp_image_path . '/thumbnail/' . $image_name);

        if(headers_sent()){
          foreach(headers_list() as $header){
            header_remove($header);
          }
        }

        header('Content-Type: application/json');

        $result = array('success' => true,
                        'file' => $this->request->getPost()->image);
        die(json_encode($result));

    }

}
